package server;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.sql.Date;
import java.util.List;

import db.MessageDAO;
import entities.Location;
import entities.Message;

public class Connection implements Runnable {
	private BufferedReader input;
	private PrintWriter output;
	private Socket incoming;
	private MessageDAO db;
	private Statistics stats;

	/**
	 * This thread handles the specific connection it was assigned to by the
	 * connectionHandler
	 * @param db 
	 */
	public Connection(Socket incoming, MessageDAO db) {
		this.incoming = incoming;
		this.db = db;
		stats = Statistics.getInstance();
	}

	public void poll() throws IOException {
		output.println(ServerConstants.OK);
		String responseLine = input.readLine();
		if (responseLine == null) {
			System.out.println("No message was received, ERROR in connection");
		}
		else {
			String[] split = responseLine.split(";");
			trimArray(split);
			int senderId = Integer.parseInt(split[0]);
			double latitude = Double.parseDouble(split[1]);
			double longitude = Double.parseDouble(split[2]);
			List<Message> msgs = db.getMessagesForRecipientLocation(senderId,
					new Location(latitude, longitude));
			for (Message msg : msgs) {
				output.println(msg);
			}
		}
	}

	public void trimArray(String[] array){
		for(int i = 0; i< array.length; i ++){
			array[i].trim();
		}
	}
	
	public void send() throws IOException {
		output.println(ServerConstants.OK);
		String responseLine = input.readLine();
		if (responseLine == null) {
			System.out.println("No message was recived, ERROR in connection");
		}
		else {
			String[] split = responseLine.split(";");
			trimArray(split);
			int id = Integer.parseInt(split[0]);
			int senderId = Integer.parseInt(split[1]);
			double latitude = Double.parseDouble(split[2]);
			double longitude = Double.parseDouble(split[3]);
			long timeOfOrigin = System.currentTimeMillis();
			long timeOfExpiry = System.currentTimeMillis() + 1000;
			String message = split[4];

			db.addMessage(new Message(id, senderId, new Location(latitude,
					longitude), new Date(timeOfOrigin), new Date(timeOfExpiry),
					message));
		}
	}

	public void run() {		
		String responseLine = "";
		try {
			// creates the new connection Thread with an input and output
			// stream
			input = new BufferedReader(new InputStreamReader(
					incoming.getInputStream()));
			output = new PrintWriter(incoming.getOutputStream(), true);
			responseLine = input.readLine();
			if (responseLine == null) {
				System.out.println("No message was recived, ERROR in connection");
			}
			else if (responseLine.equals(ServerConstants.POLL)) {
				long startTime = System.currentTimeMillis();
				poll();
				long endTime = System.currentTimeMillis();
				stats.logPoll(endTime - startTime);
				
			}
			else if (responseLine.equals(ServerConstants.SEND)) {
				long startTime = System.currentTimeMillis();
				send();
				long endTime = System.currentTimeMillis();
				stats.logSend(endTime - startTime);
			}
		}
		catch (IOException e) {
			e.printStackTrace();
		}
		try {
			input.close();
			output.close();
			incoming.close();
		}
		catch (IOException e) {
			e.printStackTrace();
		}
	}
}
